package com.dream.dynamic_datasource.filter;


import com.alibaba.fastjson.JSON;
import com.dream.dynamic_datasource.constract.JsonResult;
import com.dream.dynamic_datasource.entity.user.User;
import com.dream.dynamic_datasource.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: Luo
 * @create: 2020-07-14 15:54
 */
@Component
public class LoginFilter implements Filter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
//        rep.setHeader("Access-Control-Allow-Origin", rep.getHeader("Origin"));
        rep.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers","Access-Control-Allow-Headers, content-type,x-requested-with,Authorization, x-ui-request,lang");
        if(request.getRequestURI().contains("login") || request.getRequestURI().contains("frontEnd/projectProperty")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            User user = jwtUtil.checkJWT();
            if(user==null){
                JsonResult jsonResult = new JsonResult(3, "token is overdue");
                String jsonString = JSON.toJSONString(jsonResult);
                rep.getWriter().write(jsonString);
            }else {
                filterChain.doFilter(servletRequest, servletResponse);
            }

        }
    }
}

